Online-Academy

Look, Read, Understand, Apply

Menu

Serlvet - Passing data to servlet from HTML form.

Following program shows how to pass data from HTML form to servlet and process the passed values in the servlet. The method getParameter() of the request object of class HttpServletRequest is used to access user provided data. The method getParameter() take name of control (like text field) of HTML form.

String name = request.getParameter("tname");

To send data or text to the user, object of HttpServletResponse is used. Object of class PrintWriter is created using object of class HttpServletResponse;

PrintWriter pw = response.getWrite();
pw.write("Hello :"+name);

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/abc")
public class abc extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public abc() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());

	PrintWriter pp = response.getWriter();
	pp.write("Hello How do you do?");
	
	String name= request.getParameter("tname");
	String address = request.getParameter("taddress");
	
	if(name.length()>0 && address.length()>0 && 
	request.getParameter("tage").length()>0) {
		int age = Integer.parseInt(request.getParameter("tage"));
		if(age > 10 && age <20)
			pp.write("Hello: "+name+" You are teenager");
			else pp.write("Hello: "+name+" You are a adult");
	
	}else pp.write("Something is missing!!!");

	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException {
		doGet(request, response);
	}
}

The servlet name is assigned to the action property of the form, Servlet will process the form data. Here in the form three text fields are created to take name, address and age values from the user. Servlet abc processes the provided values.